package com.quanyan.travel.component.mq;

import com.alibaba.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import com.alibaba.rocketmq.common.message.MessageExt;
import com.quanyan.common.constants.Constants;
import com.quanyan.mq.enums.MqConsumerStatus;
import com.quanyan.mq.mq.consumer.AbstractMqConsumer;
import com.quanyan.mq.mq.consumer.MqTopic;
import com.quanyan.orderpay.service.OrderPayService;
import com.quanyan.travel.constants.OutdoorConstants;
import com.quanyan.travel.service.TravelOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Random;

/**
 * Created by xiaoxiao on 16/6/13.
 */
//@Component(value = "travelPayMq")
public class TravelPayMq extends AbstractMqConsumer {

    private final static Logger logger = LoggerFactory.getLogger(TravelPayMq.class);

    @Value("${mq.nameServer.address}")
    private String nameServerAddress;

    @Autowired
    private TravelOrderService travelOrderService;

    @PostConstruct
    void run() {
        super.start();
    }

    @Override
    protected MqConsumerStatus process(List<MessageExt> messages, ConsumeConcurrentlyContext context) {
        /**
         * 实现自己的逻辑业务
         *
         * */
        /**
         *  默认msgs里只有一条消息，可以通过设置consumeMessageBatchMaxSize参数来批量接收消息
         *  consumer.setConsumeMessageBatchMaxSize(X);
         */
        MessageExt messageExt = messages.get(0);
        //处理订单系统支付成功消息
        if(OrderPayService.TOPIC_ORDER_STATUS_NOTIFY.equals(messageExt.getTopic()) && Constants.TRAVEL_SYSTEM_CODE.equals(messageExt.getTags())){
            logger.info("开始消费订单支付成功消息-------");
            travelOrderService.payCallback(messageExt);
        }
        return MqConsumerStatus.CONSUMER_SUCCESS;
    }

    @Override
    protected String getConsumerGroup() {
        return OutdoorConstants.TRAVEL_GROUP_ORDER_PAY;
    }

    @Override
    protected String getNameServerAddress() {
        return nameServerAddress;
    }

    @Override
    protected String getInstanceName() {
        return OutdoorConstants.TRAVEL_INSTANCE_ORDER_PAY + (new Random().nextInt(9999 - 1000 + 1)+1000);
    }

    @Override
    protected MqTopic[] getMqTopics() {
        MqTopic[] mqTopics = new MqTopic[1];
        mqTopics[0] = new MqTopic(OrderPayService.TOPIC_ORDER_STATUS_NOTIFY, Constants.TRAVEL_SYSTEM_CODE);
        return mqTopics;
    }
}
